package com.chhuang.utils.file;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.lang3.StringUtils;

import com.chhuang.utils.string.StringUtil;

/**
 * 文件操作工具类
 * @author 黄晨
 * @date 2013-4-2
 *
 */
public class FileUtil {
	
	/**
	 * 获取文件后缀名
	 * @param filename
	 * @return
	 */
	public static String getFileSuffix(String filename) {
		if(StringUtil.isEmpty(filename)) {
			return null;
		}
		
		return filename.substring(filename.lastIndexOf(".") + 1);
	}
	
	/**
	 * 得到文件的后缀名
	 * @param file
	 * @return
	 */
	public static String getFileSuffix(File file) {
		if(file==null){
			return null;
		}

		return getFileSuffix(file.getName());
	}
	
	/**
	 * 修改文件的后缀名
	 * @param filename
	 * @param type
	 * @return
	 */
	public static String replaceFileType(String filename, String type) {
		if(StringUtil.isEmpty(filename)) {
			return null;
		}
		String newFilename;
		if(filename.indexOf(".") < 0) {
			newFilename = filename + type;
		} else {
			newFilename = filename.substring(0, filename.lastIndexOf(".") + 1) + type;
		}
	
		return newFilename;
	}
	
	/**
	 * 文件名添加后缀
	 * @param filename
	 * @param suffix
	 * @return
	 */
	public static String filenameAddSuffix(String filename, String suffix) {
		if(StringUtil.isEmpty(filename)) {
			return "";
		}
		
		int typeIndex = filename.lastIndexOf(".");
		
		String namePre = filename.substring(0, typeIndex);
		String type = filename.substring(typeIndex, filename.length());
		
		String newName = namePre + suffix + type;
		
		return newName;
	}
	
	/**
	 * 删除文件或目录
	 * @param file
	 */
	public static void deleteAll(File file) {
		if (!file.exists()) {
			return;
		}
		if (file.isFile()) {
			file.delete();
		} else {
			File[] files = file.listFiles();
			for (int i = 0; i < files.length; i++)
				deleteAll(files[i]);
		}
	}

	/**
	 * 根据流判断流的编码格式
	 * @param is
	 * @return
	 */
	public static String getStreamCode(InputStream is) {
		String charset = null;
		byte[] first3Bytes = new byte[3];
		try {
			is.mark(0);
			int read = is.read(first3Bytes, 0, 3);
			if (read != -1) {
				if ((first3Bytes[0] == -1) && (first3Bytes[1] == -2)) {
					charset = "UTF-16LE";
				} else if ((first3Bytes[0] == -2) && (first3Bytes[1] == -1)) {
					charset = "UTF-16BE";
				} else if ((first3Bytes[0] == -17) && (first3Bytes[1] == -69)
						&& (first3Bytes[2] == -65)) {
					charset = "UTF-8";
				} else {
					is.reset();

					while ((read = is.read()) != -1) {
						if (read >= 240)
							break;
						if ((128 <= read) && (read <= 191))
							break;
						if ((192 <= read) && (read <= 223)) {
							read = is.read();
							if ((128 > read) || (read > 191))
								break;
							continue;
						} else if ((224 <= read) && (read <= 239)) {
							read = is.read();
							if ((128 > read) || (read > 191))
								break;
							read = is.read();
							if ((128 > read) || (read > 191))
								break;
							charset = "UTF-8";
						}

					}

				}

			}

			if (null == charset)
				charset = "GBK";
		} catch (Exception e) {
			e.printStackTrace();
		}

		return charset;
	}

	/**
	 * 获取文件的编码格式
	 * @param file
	 * @return
	 */
	public static String getFileCode(File file) {
		InputStream is = null;
		String code = null;
		try {
			is = new BufferedInputStream(new FileInputStream(file));
			code = getStreamCode(is);
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return code;
	}
	
	/**
	 * 根据传入的文件参数创建文件
	 * @param filename 文件名，可带后缀可不带
	 * @param filePath 文件保存路径
	 * @param suffix 文件后缀名
	 * 
	 * @return 创建的文件名
	 */
	public static String createFile(String filePath, String filename, String suffix) {
		
		String newFilename = filename;
		if(suffix != null && !"".equals(suffix)) {
			newFilename = replaceFileType(filename, "." + suffix);
		} else {
			int pointIndex = filename.lastIndexOf(".");
			if(pointIndex==-1){
				newFilename = filename;
			}else{
				newFilename = filename.substring(0, pointIndex);
			}
		}
		
		String tmpLastLitter = filePath.substring(filePath.length() -1, filePath.length());
		if(!(tmpLastLitter.equals("/") || tmpLastLitter.equals("\\"))) {
			filePath += "/";
		}
		
		File dir = new File(filePath);
		
		if(!dir.exists()) {
			dir.mkdir();
		}
		
		String absFilename = filePath + newFilename;
		
		File file = new File(absFilename);
		
		if(file.exists()) {
			file.deleteOnExit();
		}
		
		try {
			file.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return absFilename;
	}
	
	/**
     * 获得文件大小，单位字节
     * @param fileAbPath
     * @return
     */
    public static int getFileSizeOrSo(String fileAbPath) {
    	if(StringUtil.isEmpty(fileAbPath)) {
    		return 0;
    	}
    	
    	File file = new File(fileAbPath);
    	
    	if(!file.exists()) {
    		return 0;
    	}
    	
    	int size = 0;
    	
    	FileInputStream fis = null;
    	
    	try {
			fis = new FileInputStream(file);
			
			size = fis.available();
			
			fis.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
    	
    	return size;
    }
    
    /**
     * 创建文件目录
     * @param filePath
     */
    public static File makeFilePath(String filePath){
    	File file = null;
    	if(StringUtils.isNotBlank(filePath)){
    		file = new File(filePath);
	    	makeFilePath(file);
    	}
    	return file;
    }
    
    /**
     * 创建文件目录
     * @param file
     */
    public static void makeFilePath(File file){
    	if(file!=null && !file.exists()){
    		file.getParentFile().mkdirs();
    	}
    }
    
}
